import myglobal from './myglobal'
import * as store from './reducers/partsSlice';
const fs = window.require('fs')
const sessionRestore = {
  savePath: myglobal['home'] + '/sessionRestore.json',
  previousState: null,
  save: function (state) {
    var stateString = JSON.stringify(state);
    // console.log(stateString);
    // console.log(sessionRestore.savePath);
    fs.writeFileSync(sessionRestore.savePath, stateString);
  },
  restore: function (dispatch) {
    // window.tasklist = new TaskList();
    var savedStringData;
    try {
      savedStringData = fs.readFileSync(sessionRestore.savePath, 'utf-8');
    } catch (e) {
      console.warn('failed to read session restore data', e);
    }

    try {
      // first run, show the tour
      if (!savedStringData) {
        // tasklist.add();//#new blank task
        let url = 'file://' + myglobal['home'] + '/pages/index.html';
        dispatch(store.partsSlice.actions.ADD_TAB({ url }))
        return;
      }

      var data = JSON.parse(savedStringData);
      // tasklist.add(data);//new task
      // browserUI.switchToTask(tasklist.task.id);
      console.log(data)
      // console.log(tasklist);
      dispatch(store.partsSlice.actions.INIT_DATA(data))
      return;
    } catch (e) {
      // an error occured while restoring the session data

      console.error('restoring session failed: ', e);

      var backupSavePath = window
        .require('path')
        .join(
          myglobal['home'],
          'sessionRestoreBackup-' + Date.now() + '.json'
        );

      fs.writeFileSync(backupSavePath, savedStringData);

      // destroy any tabs that were created during the restore attempt

      // create a new tab with an explanation of what happened
      // var newTask = tasklist.add();
      let url = 'file://' + myglobal['home'] + '/pages/index.html'
      dispatch(store.partsSlice.actions.ADD_TAB({ url }))
    }
  },
};

// TODO make this a preference
// sessionRestore.restore();
// setInterval(sessionRestore.save, 30000);
export default sessionRestore;
